package org.anupta.game.server.game;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.anupta.game.main.Main;
import org.anupta.game.server.game.client.GameClient;
import org.anupta.game.utils.others.Config;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class GameServer {
	private IoAcceptor acceptor = new NioSocketAcceptor();
	private List<Integer> accWaiting = new ArrayList<Integer>();
	private List<GameClient> connected = new ArrayList<GameClient>();
	
	public GameServer(){
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF8"),LineDelimiter.NUL, new LineDelimiter("\n\0"))));
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, Config.TIME_OUT);
		acceptor.setHandler(new GameHandler());
	}
	
	public void bind(int port){
		try {
			acceptor.bind(new InetSocketAddress(Config.GAME_IP,port));
		} catch (IOException e) {
			Main.err.write(e);
		}
	}
	
	public void close(){
		acceptor.unbind();
		acceptor.dispose(true);
	}

	public List<Integer> getAccWaiting() {
		return accWaiting;
	}
	
	public boolean containAccWaiting(int guid){
		if(accWaiting.contains(guid)){
			return true;
		}
		return false;
	}

	public void setAccWaiting(List<Integer> accWaiting) {
		this.accWaiting = accWaiting;
	}
	
	public void addAccWaiting(int guid){
		accWaiting.add(guid);
		Main.out.println(new StringBuilder("Waiting account added : ").append(guid).toString());
	}
	
	public void remAccWaiting(int guid){
		accWaiting.remove((Object)guid);
		Main.out.println(new StringBuilder("Waiting account removed : ").append(guid).toString());
	}

	public List<GameClient> getConnected() {
		return connected;
	}

	public void setConnected(List<GameClient> connected) {
		this.connected = connected;
	}
}
